package com.xy.mainp.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 格式化时间的工具类
 * Created by Y-bao on 2016/4/10 19:49.
 */
public class TimeUtil {
    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM-dd");
        }
    };
    public static SimpleDateFormat F_N_YYYYMMddHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static SimpleDateFormat F_N_YYYYMMddHHMM = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static SimpleDateFormat F_N_YYYYMMdd = new SimpleDateFormat("yyyy-MM-dd");
    public static SimpleDateFormat F_N_MMddHHMM = new SimpleDateFormat("MM-dd HH:mm");
    public static SimpleDateFormat F_N_MMddHHMM2 = new SimpleDateFormat("MM.dd HH:mm");
    public static SimpleDateFormat F_N_HMM = new SimpleDateFormat("H:mm");
    public static SimpleDateFormat F_P_MMdd = new SimpleDateFormat("MM.dd");
    public static SimpleDateFormat F_ZN_MMdd = new SimpleDateFormat("MM月dd日");
    public static SimpleDateFormat F_ZN_MMdd2 = new SimpleDateFormat("MM-dd");
    public static SimpleDateFormat F_ZN_Mdd = new SimpleDateFormat("M.dd");

    public static String getLogicTime(Date date, String[] dayName) {
        String logicDay = "";
        try {
            logicDay = F_ZN_MMdd.format(date);//月日

            Calendar cal = Calendar.getInstance();//当前日期

            cal.add(Calendar.DATE, 0);
            for (int i = 0; i < dayName.length; i++) {
                if (F_ZN_MMdd.format(cal.getTime()).equals(logicDay)) {
                    logicDay = dayName[i];
                    break;
                }
                cal.add(Calendar.DATE, -1);//减一
            }
        } catch (Exception e) {
            logicDay = "";
        }
        return logicDay;
    }

    public static String getLogicTime(Date date, String dayName, SimpleDateFormat format) {
        String logicDay = "";
        try {
            logicDay = format.format(date);//月日

            Calendar cal = Calendar.getInstance();//当前日期

            cal.add(Calendar.DATE, 0);
            if (format.format(cal.getTime()).equals(logicDay)) {
                logicDay = dayName;
            }
//            cal.add(Calendar.DATE, -1);//减一
        } catch (Exception e) {
            logicDay = "";
        }
        return logicDay;
    }

    public static String getPrTime(Date date, String[] dayName) {
        String prDay = "";
        try {
            prDay = F_P_MMdd.format(date);//月日

            Calendar cal = Calendar.getInstance();//当前日期

            cal.add(Calendar.DATE, 0);
            for (int i = 0; i < dayName.length; i++) {
                if (F_P_MMdd.format(cal.getTime()).equals(prDay)) {
                    String time = F_N_HMM.format(date);
                    String[] cmd = time.split(":");
                    if (cmd.length >= 2 && cmd[1].equalsIgnoreCase("00")) {
                        time = cmd[0] + "时";
                    }
                    prDay = dayName[i] + time;
                    break;
                }
                cal.add(Calendar.DATE, 1);//加一
            }
        } catch (Exception e) {
            prDay = "";
        }
        return prDay;
    }

    /**
     * @param time
     * @param toFormatStr
     * @return
     */
    public static String getDateStr(String time, String toFormatStr) {
        try {
            Date dayDate = F_N_YYYYMMddHHMMSS.parse(time);
            SimpleDateFormat toFormat = new SimpleDateFormat(toFormatStr);
            return toFormat.format(dayDate);
        } catch (Exception e) {

        }
        return "";
    }

    public static String getDateStr(String time, SimpleDateFormat toFormat) {
        try {
            Date dayDate = F_N_YYYYMMddHHMMSS.parse(time);
            return toFormat.format(dayDate);
        } catch (Exception e) {

        }
        return "";
    }

    public static String getDateStr(Date dayDate, SimpleDateFormat toFormat) {
        try {
            return toFormat.format(dayDate);
        } catch (Exception e) {

        }
        return "";
    }

    public static Date getDate(String time, SimpleDateFormat fromFormat) {
        try {
            return fromFormat.parse(time);
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 获取两个日期间的间隔
     *
     * @param stime
     * @param etime
     * @return
     */
    public static long getTwoDayIntervals(String stime, String etime) {
        long end = 0;
        long start = 0;
        try {
            end = F_N_YYYYMMddHHMMSS.parse(stime).getTime();
            start = F_N_YYYYMMddHHMMSS.parse(etime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return Math.abs((end - start));
    }

    /**
     * 将时间簇间隔转换化成天时分秒
     *
     * @param timeMillis
     * @return
     */
    public static String timeMillisFormat(long timeMillis) {
        long allsec = timeMillis / 1000;
        long p = 60 * 60 * 24;
        long days = allsec / p;
        long stimeMillis = allsec % p;
        p = 60 * 60;
        long hours = stimeMillis / p;
        stimeMillis = stimeMillis % p;
        p = 60;
        long minutes = stimeMillis / p;
        stimeMillis = stimeMillis % p;
        String str = "";
        if (days == 0) {
            str = String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", stimeMillis);
        } else {
            str = String.format("%02d", days) + "天 " + String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", stimeMillis);
        }
        return str;
    }

    public static int getWeekNem(Calendar cal) {
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w <= 0)
            w = 7;
        return w;
    }

    public static int getWeekNem(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        return getWeekNem(cal);
    }

    /**
     * 获取当前星期数
     **/
    public static int getWeekNemNow() {
        return getWeekNem(Calendar.getInstance());
    }

    // millis为毫秒
    public static String friendlyTime(long millis) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currDate = new Date(millis);
        String str = formatter.format(currDate);

        Date time = toDate(str);
        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) {
                long minutes = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1);
                if (minutes > 1) {
                    ftime = minutes + "分钟前";
                } else {
                    ftime = "刚刚";
                }
            } else {
                ftime = hour + "小时前";
            }
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) {
                long minutes = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1);
                if (minutes > 1) {
                    ftime = minutes + "分钟前";
                } else {
                    ftime = "刚刚";
                }
            } else {
                ftime = hour + "小时前";
            }
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2) {
            ftime = convertDateToString(millis);
        }
        return ftime;
    }

    public static String convertDateToString(long date) {
        long ldate = date;
        String weekdays;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(ldate));
        String years = String.valueOf(calendar.get(Calendar.YEAR));
        String mouth = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        String day = String.valueOf(calendar.get(calendar.DAY_OF_MONTH));
        int weekday = Integer.valueOf(calendar.get(calendar.DAY_OF_WEEK));

        if (Calendar.MONDAY == weekday) {
            weekdays = "周一";
        } else if (Calendar.TUESDAY == weekday) {
            weekdays = "周二";
        } else if (Calendar.WEDNESDAY == weekday) {
            weekdays = "周三";
        } else if (Calendar.THURSDAY == weekday) {
            weekdays = "周四";
        } else if (Calendar.FRIDAY == weekday) {
            weekdays = "周五";
        } else if (Calendar.SATURDAY == weekday) {
            weekdays = "周六";
        } else if (Calendar.SUNDAY == weekday) {
            weekdays = "周日";
        } else {
            weekdays = "";
        }
        int hour = calendar.get(calendar.HOUR_OF_DAY);
        int minute = calendar.get(calendar.MINUTE);

        return years + "-" + mouth + "-" + day + " " + weekdays + " " + FormatZero(hour) + ":" + FormatZero(minute);
    }

    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String FormatZero(int a) {
        if (a == 0)
            return "00";
        if (a < 10)
            return "0" + a;
        return a + "";
    }
}
